<template>
  <div class="tree-box">
    <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <div class="custom-tree-node" slot-scope="{ node, data }">
        <template v-if="data.id === 0">
          {{ node.label }}
          <span>
            <el-button
              v-if="data.children.length === 0"
              size="mini"
              @click="() => appendSon(data)"
              icon="el-icon-plus"
              >添加子节点</el-button
            >
          </span>
        </template>
        <template v-else>
          <input v-model="data.targetName" placeholder="目标参数名" />
          <input v-model="data.srcName" placeholder="原始参数名" />
          <input v-model="data.example" placeholder="示例值" />
          <span>
            <el-button
              type="text"
              size="mini"
              @click="() => append(node, data)"
              icon="el-icon-plus"
              >添加节点</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="() => appendSon(data)"
              icon="el-icon-plus"
              >添加子节点</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
              icon="el-icon-minus"
              >移除</el-button
            >
          </span>
        </template>
      </div>
    </el-tree>
    <el-button type="primary" @click="submit">提交</el-button>
  </div>
</template>
 
<script>
let id = 1000;
export default {
  data() {
    return {
      treeData: [
        {
          id: 0,
          label: "入参映射配置",
          children: [
            {
              targetName: null,
              srcName: null,
              example: null,
              children: []
            },
          ],
        },
      ],
    };
  },
  methods: {
    append(node, data) {
      var parent = node.parent;
      const newChild = { id: id++, children: [] };
      parent.data.children.push(newChild);
    },
    appendSon(data) {
      const newChild = { id: id++, children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    submit() {
      alert(JSON.stringify(this.treeData));
      console.log(JSON.stringify(this.treeData));
    },
  },
};
</script>
<style scoped>
.el-tree >>> div >>> .el-tree-node__content {
  margin: 10px;
}

.custom-tree-node {
    justify-content: space-between;
    font-size: 14px;
    padding-right: 2px;
}
</style>